{% extends "pc/base.html" %}

{% block content %}
<!-- 插件列表 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h5 class="mb-0">插件列表</h5>
</div>

<div class="plugins-container-wrapper">
    <div class="plugins-main-content w-100">
        <div class="plugins-loading" id="plugins-loading">
            <div class="d-flex justify-content-center py-5">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
            </div>
        </div>

        <div id="plugins-container"></div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
const getToken = () => new URLSearchParams(window.location.search).get('token');

function loadPlugins() {
    const container = document.getElementById('plugins-container');
    const loading = document.getElementById('plugins-loading');
    
    loading.style.display = 'block';
    container.innerHTML = '';
    
    if (window.socket) {
        window.socket.emit('get_plugins_info');
    } else {
        loading.style.display = 'none';
        container.innerHTML = '<div class="alert alert-warning">无法连接到服务器</div>';
    }
}

function updatePluginsInfo(plugins) {
    const pluginsContainer = document.getElementById('plugins-container');
    const pluginsLoading = document.getElementById('plugins-loading');
    
    pluginsLoading.style.display = 'none';
    
    if (!plugins || plugins.length === 0) {
        pluginsContainer.innerHTML = '<div class="alert alert-info">未发现任何插件</div>';
        return;
    }
    
    const pluginsByDirectory = {};
    plugins.forEach(plugin => {
        const directory = plugin.directory || (plugin.name.startsWith('example/') ? 'example' : 
                           plugin.name.startsWith('system/') ? 'system' : 'other');
        if (!pluginsByDirectory[directory]) {
            pluginsByDirectory[directory] = [];
        }
        pluginsByDirectory[directory].push(plugin);
    });
    
    const directoryOrder = ['system', 'example', 'alone'];
    const sortedDirectories = Object.keys(pluginsByDirectory).sort((a, b) => {
        const indexA = directoryOrder.indexOf(a);
        const indexB = directoryOrder.indexOf(b);
        if (indexA === -1 && indexB === -1) return a.localeCompare(b);
        if (indexA === -1) return 1;
        if (indexB === -1) return -1;
        return indexA - indexB;
    });
    
    let html = '';
    sortedDirectories.forEach(directory => {
        const directoryPlugins = pluginsByDirectory[directory];
        if (directoryPlugins && directoryPlugins.length > 0) {
            const directoryNames = {
                'system': '系统插件',
                'example': '示例插件', 
                'alone': '独立插件',
                'other': '其他插件'
            };
            const dirDisplayName = directoryNames[directory] || directory.toUpperCase();
            
            html += `
            <div class="mb-4">
                <div class="directory-title" onclick="togglePluginFolder('${directory}')">
                    <div class="directory-badge">
                        <i class="bi bi-chevron-right folder-chevron" id="folder-chevron-${directory}"></i>
                        <i class="bi bi-folder-fill"></i>
                        ${dirDisplayName}
                        <span class="count-badge">${directoryPlugins.length}</span>
                    </div>
                </div>
                <div class="directory-plugins" id="directory-plugins-${directory}">`;
            
            directoryPlugins.forEach(plugin => {
                const statusClass = plugin.status === 'loaded' ? 'loaded' : (plugin.status === 'disabled' ? 'disabled' : 'error');
                let statusBadge = '';
                if (plugin.status === 'loaded') {
                    statusBadge = `<span class="badge bg-success plugin-badge"><i class="bi bi-check-circle-fill"></i> 已加载</span>`;
                } else if (plugin.status === 'disabled') {
                    statusBadge = `<span class="badge bg-warning plugin-badge"><i class="bi bi-dash-circle-fill"></i> 已禁用</span>`;
                } else {
                    statusBadge = `<span class="badge bg-danger plugin-badge"><i class="bi bi-exclamation-triangle-fill"></i> 错误</span>`;
                }
                let handlerCountBadge = '';
                if (plugin.status === 'loaded') {
                    const handlerCount = plugin.handlers || 0;
                    handlerCountBadge = `<span class="badge bg-secondary plugin-badge"><i class="bi bi-code-slash"></i> ${handlerCount}个处理器</span>`;
                }
                
                let errorHtml = '';
                if (plugin.status === 'error' && plugin.error) {
                    errorHtml = `<div class="plugin-error">${plugin.error}</div>`;
                    if (plugin.traceback) {
                        errorHtml += `<div class="plugin-error mt-2">${plugin.traceback}</div>`;
                    }
                }
                let handlersHtml = '';
                if (plugin.status === 'loaded' && plugin.handlers_list && plugin.handlers_list.length > 0) {
                    const handlers_owner_only = plugin.handlers_owner_only || {};
                    const handlers_group_only = plugin.handlers_group_only || {};
                    handlersHtml = `
                    <div class="plugin-handlers">
                        <div class="handlers-container">
                            ${plugin.handlers_list.map(handler => {
                                const isOwnerOnly = handlers_owner_only[handler] === true;
                                const isGroupOnly = handlers_group_only[handler] === true;
                                let handlerClass = 'handler-item handler-item-public';
                                let handlerIcon = '';
                                if (isOwnerOnly) {
                                    handlerClass = 'handler-item handler-item-owner';
                                    handlerIcon = '<i class="bi bi-shield-lock-fill"></i> ';
                                }
                                if (isGroupOnly) {
                                    handlerClass = 'handler-item handler-item-group';
                                    handlerIcon = '<i class="bi bi-people-fill"></i> ';
                                }
                                if (isOwnerOnly && isGroupOnly) {
                                    handlerIcon = '<i class="bi bi-shield-lock-fill"></i> <i class="bi bi-people-fill"></i> ';
                                }
                                let titleText = '所有人可用';
                                if (isOwnerOnly && isGroupOnly) {
                                    titleText = '主人专属且仅限群聊';
                                } else if (isOwnerOnly) {
                                    titleText = '主人专属命令';
                                } else if (isGroupOnly) {
                                    titleText = '仅限群聊使用';
                                }
                                return `<span class="${handlerClass}" title="${titleText}">${handlerIcon}${handler}</span>`;
                            }).join('')}
                        </div>
                    </div>`;
                }
                let displayName = plugin.name;
                if (displayName.includes('/')) {
                    const parts = displayName.split('/');
                    if (parts.length >= 3) {
                        displayName = `${parts[1]} <span class="text-secondary">(${parts[2]})</span>`;
                    } else {
                        displayName = parts[parts.length - 1];
                    }
                }
                let priorityDisplay = '';
                if (plugin.status === 'loaded') {
                    const priority = plugin.priority !== undefined ? plugin.priority : 10;
                    priorityDisplay = `<span class="plugin-priority"><i class="bi bi-sort-numeric-down"></i> ${priority}</span>`;
                }
                let pathDisplay = `<span class="plugin-path" title="${plugin.path}">${plugin.path.split('/').slice(-3).join('/')}</span>`;
                let timeDisplay = '';
                if (plugin.last_modified) {
                    timeDisplay = `<span class="plugin-path text-muted ms-2"><i class="bi bi-clock-history"></i> ${plugin.last_modified}</span>`;
                }
                
                let toggleSwitch = '';
                if (plugin.status === 'loaded' || plugin.status === 'disabled') {
                    const isEnabled = plugin.enabled !== false && plugin.status === 'loaded';
                    const switchId = `plugin-switch-${plugin.path.replace(/[^a-zA-Z0-9]/g, '_')}`;
                    toggleSwitch = `<div class="form-check form-switch plugin-toggle-switch">
                                        <input class="form-check-input" type="checkbox" 
                                               id="${switchId}" ${isEnabled ? 'checked' : ''}
                                               onchange="togglePluginSwitch('${plugin.path}', this)">
                                        <label class="form-check-label" for="${switchId}">
                                            ${isEnabled ? '已启用' : '已禁用'}
                                        </label>
                                    </div>`;
                }
                
                html += `
                <div class="card plugin-card ${statusClass}">
                <div class="plugin-content">
                        <div class="plugin-info">
                            <div class="plugin-name-container">
                                <h6 class="mb-0 me-2">${displayName}</h6>
                                ${priorityDisplay}
                                ${pathDisplay}
                                ${timeDisplay}
                            </div>
                                <div class="plugin-badges">
                                    ${statusBadge}
                                ${handlerCountBadge}
                                ${toggleSwitch}
                            </div>
                        </div>
                        ${handlersHtml}
                        ${errorHtml}
                    </div>
                </div>`;
            });
            
            html += `</div></div>`;
        }
    });
    
    pluginsContainer.innerHTML = html;
}

function togglePluginFolder(directory) {
    const header = document.querySelector(`[onclick="togglePluginFolder('${directory}')"]`);
    const content = document.getElementById(`directory-plugins-${directory}`);
    const chevron = document.getElementById(`folder-chevron-${directory}`);
    
    if (content && header && chevron) {
        const isExpanded = content.classList.contains('expanded');
        
        if (isExpanded) {
            content.classList.remove('expanded');
            header.classList.remove('expanded');
            chevron.classList.remove('bi-chevron-down');
            chevron.classList.add('bi-chevron-right');
        } else {
            content.classList.add('expanded');
            header.classList.add('expanded');
            chevron.classList.remove('bi-chevron-right');
            chevron.classList.add('bi-chevron-down');
        }
    }
}

async function togglePluginSwitch(pluginPath, switchElement) {
    const action = switchElement.checked ? 'enable' : 'disable';
    const label = switchElement.nextElementSibling;
    const originalState = { checked: !switchElement.checked, text: label.textContent };
    
    switchElement.disabled = true;
    label.textContent = '处理中...';
    
    try {
        const response = await fetch(`/web/api/plugin/toggle?token=${getToken()}`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ path: pluginPath, action })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showToast(result.message, 'success');
            label.textContent = action === 'enable' ? '已启用' : '已禁用';
            updatePluginCardStatus(switchElement, action === 'enable' ? 'loaded' : 'disabled');
            
            if (result.new_path) {
                switchElement.setAttribute('onchange', `togglePluginSwitch('${result.new_path}', this)`);
            }
            
            switchElement.disabled = false;
        } else {
            throw new Error(result.message || '操作失败');
        }
    } catch (error) {
        showToast(error.message, 'error');
        switchElement.checked = originalState.checked;
        label.textContent = originalState.text;
        switchElement.disabled = false;
    }
}

function updatePluginCardStatus(switchElement, newStatus) {
    const pluginCard = switchElement.closest('.plugin-card');
    if (!pluginCard) return;
    
    pluginCard.classList.remove('loaded', 'disabled', 'error');
    pluginCard.classList.add(newStatus);
    
    const statusBadge = pluginCard.querySelector('.plugin-badges .badge');
    if (statusBadge) {
        const statusConfig = {
            loaded: { class: 'bg-success', icon: 'check-circle-fill', text: '已加载' },
            disabled: { class: 'bg-warning', icon: 'dash-circle-fill', text: '已禁用' },
            error: { class: 'bg-danger', icon: 'exclamation-triangle-fill', text: '错误' }
        };
        const config = statusConfig[newStatus];
        if (config) {
            statusBadge.className = `badge ${config.class} plugin-badge`;
            statusBadge.innerHTML = `<i class="bi bi-${config.icon}"></i> ${config.text}`;
        }
    }
}

function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    const isSuccess = type === 'success';
    toast.className = `alert alert-${isSuccess ? 'success' : 'danger'} position-fixed`;
    toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 250px;';
    toast.innerHTML = `<div class="d-flex align-items-center">
        <i class="bi bi-${isSuccess ? 'check-circle' : 'exclamation-circle'}-fill me-2"></i>
        <div>${message}</div>
    </div>`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 3000);
}

document.addEventListener('DOMContentLoaded', function() {
    window.updatePluginsInfo = updatePluginsInfo;
    window.togglePluginSwitch = togglePluginSwitch;
    initSocket('plugins');
});
</script>

<style>
.plugin-toggle-switch {
    display: flex;
    align-items: center;
    gap: 10px;
    margin: 0 0 0 8px;
    padding: 0;
}
.plugin-toggle-switch .form-check-input {
    cursor: pointer;
    width: 3rem;
    height: 1.5rem;
    border: 2px solid #cbd5e0;
    margin: 0;
}
.plugin-toggle-switch .form-check-input:checked {
    background-color: #667eea;
    border-color: #667eea;
}
.plugin-toggle-switch .form-check-input:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
.plugin-toggle-switch .form-check-label {
    cursor: pointer;
    font-weight: 500;
    color: #4a5568;
    margin: 0;
    white-space: nowrap;
    font-size: 0.85rem;
}
</style>

{% endblock %}